package med;

import java.util.Iterator;
import java.util.List;

import med.config.Config;

import org.apache.commons.lang3.StringUtils;

import com.mdimension.jchronic.Chronic;

public class VectorIterator implements Iterator<Vector> {

	private List<String> data;

	private int vectorLength;

	private int idx;

	private boolean onlyFull;

	private VectorIterator(List<String> data, int vectorLength, boolean onlyFull) {
		this.data = data;
		this.vectorLength = vectorLength;
		this.onlyFull = onlyFull;
		this.idx = 0;
	}

	/**
	 * @param text
	 * @param vectorLength length of the Vectors to be created
	 * @param onlyFull
	 *            return only Vectors with full length (see <code>vectorLength</code>)
	 * @return
	 */
	public static VectorIterator getIterator(List<String> text,
			int vectorLength, boolean onlyFull) {
		return new VectorIterator(text, vectorLength, onlyFull);
	}

	@Override
	public boolean hasNext() {
		boolean result = false;
		if (idx < data.size()) {
			if (onlyFull) {
				if (idx + vectorLength < data.size()) {
					result = true;
				}
			} else {
				result = true;
			}
		}
		return result;
	}

	@Override
	public Vector next() {
		List<String> vectorData = data.subList(idx, idx + vectorLength < data
				.size() ? idx + vectorLength : data.size());
		++idx;
		return new Vector(vectorData, getFormat(vectorData));
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException();
	}

	private Format getFormat(List<String> vectorData) {
		Format fmt = Format.Unknown;
		if (Config.getInstance().isParseDatesParam()) {
			String vectorStr = StringUtils.join(vectorData, ' ').replaceAll("[^a-zA-Z0-9\\s+]", "");
			try {
				if (vectorStr.length() > 0 && Chronic.parse(vectorStr) != null) {
					fmt = Format.Date;
				}
			} catch (Exception ignore) {
			}
		}
		return fmt;
	}
}
